Skip to content

feat: register Discord command groups - #9445

Open
casama233 wants to merge 2 commits into
AstrBotDevs:masterfrom
casama233:feat/discord-command-groups
Open

feat: register Discord command groups#9445
casama233 wants to merge 2 commits into
AstrBotDevs:masterfrom
casama233:feat/discord-command-groups

Conversation

@casama233

@casama233 casama233 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Relates to #9258.

Note

This is a Draft proposal for maintainer feedback. It does not migrate any plugin commands by itself and is not requesting immediate merge.

Discord currently skips CommandGroupFilter and every child CommandFilter during application command registration. Plugins that use AstrBot command groups therefore have no discoverable Discord slash command, while plugins that flatten their command tree can consume a large part of Discord's application command quota.

The proposed mapping was discussed in #9258 before implementation:
#9258 (comment)

A separate Draft plugin migration demonstrates the intended consumer without coupling its review or merge to this core PR:
vmoranv-reborn/astrbot_plugin_pixiv_reborn#48

Modifications / 改动点

  • Register each root CommandGroupFilter as one Pycord SlashCommandGroup.
  • Register direct child commands as Discord subcommands.
  • Register one nested AstrBot group level as a Discord subcommand group.
  • Rebuild the complete AstrBot command path in leaf callbacks, so the existing waking and filter pipeline remains unchanged.
  • Keep the current optional params string on each leaf command. This avoids overlapping with the separate typed-option work in Discord 适配器增强功能 #9125.
  • Skip deeper nesting with an explicit warning because Discord only supports command -> subcommand group -> subcommand.
  • Enforce Discord's 25-option limit, name validation, duplicate handling, disabled-command filtering, and 100-character descriptions.
  • Ignore nested group metadata during the outer registry scan, ensuring the complete tree consumes only one top-level Discord command.
  • Add tests for registration count and shape, full callback paths, and unsupported deep nesting.

Scope boundary:

  • Existing flattened plugin commands are not rewritten or removed.

  • Plugins opt in only by using AstrBot's existing command_group decorators.

  • This PR is independent of the Pixiv authentication PR and can be reviewed on its own.

  • No new dependency is introduced.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

Verification steps:

make pr-test-neo

Result:

Ruff format check: passed
Ruff lint check: passed
Pytest: 12 passed
Startup smoke test on http://localhost:6185: passed
PR checks completed successfully

GitHub Actions also pass across the repository test suite, build, format check,
CodeQL, and startup smoke tests on Ubuntu, macOS, and Windows with Python
3.10–3.14.

The generated payload was also checked with the real Pycord classes. A root group with one direct command and one nested group serializes as:

/pixiv
├── search
└── user
    └── detail

The two leaf callbacks rebuild pixiv search <params> and pixiv user detail <params> respectively.


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Register AstrBot command groups as structured Discord slash commands while preserving existing command handling behavior.

New Features:

  • Map root AstrBot CommandGroupFilter instances to single Discord SlashCommandGroup entries with nested subcommand groups and subcommands.
  • Expose grouped AstrBot commands as discoverable Discord slash commands using a shared "params" string option on leaves.

Enhancements:

  • Enforce Discord naming, description length, option count limits, duplicate detection, and disabled-command filtering during command registration.
  • Normalize command and group descriptions into Discord-compliant text and centralize slash name validation logic.

Tests:

  • Add tests covering group-based registration shape and counts, full callback command-path reconstruction, and skipping of unsupported deep nesting in command groups.

@NLKASHEI

NLKASHEI commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

未来还需要增加对VUE面板的支持功能,也得加入议程,辛苦

Copy link
Copy Markdown
Contributor Author

感谢提醒,也谢谢关注这个方向 🙏

我刚又对了一下目前 master 的实现:Dashboard 的插件详情页现在已经能读取并树状展示 command group / subcommands,所以这部分基础支持目前已经具备了。

#9445 这次我先把范围聚焦在 Discord 原生 Slash Command 的注册映射,尽量避免把前端改动混在同一个 PR 里。如果后续 Vue 面板还有更具体的交互或配置需求,也很欢迎指出,我可以再单独跟进补齐。

@casama233
casama233 marked this pull request as ready for review August 11, 2026 01:43
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. area:platform The bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on. labels Aug 11, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/platform/sources/discord/discord_platform_adapter.py" line_range="565" />
<code_context>
+        Returns:
+            Whether the name can be registered with Discord.
+        """
+        return name == name.lower() and bool(re.match(r"^[-_'\w]{1,32}$", name))
+
+    @staticmethod
</code_context>
<issue_to_address>
**issue (bug_risk):** Slash command name validator allows characters Discord likely rejects (single quote), causing potential registration failures.

The regex `^[-_'\w]{1,32}$` currently allows single quotes, but Discord’s documented pattern only permits lowercase letters, digits, underscores, and hyphens (e.g. `^[a-z0-9_-]{1,32}$` or `^[\w-]{1,32}$` with the existing lowercase check). This mismatch means we may accept command names that Discord rejects with 400s at registration. Please align the regex with Discord’s constraints so invalid names are caught locally.
</issue_to_address>

### Comment 2
<location path="astrbot/core/platform/sources/discord/discord_platform_adapter.py" line_range="627" />
<code_context>
+            parent=parent,
+        )
+
+    def _create_slash_command_group(
+        self,
+        group_filter: CommandGroupFilter,
</code_context>
<issue_to_address>
**issue (complexity):** Consider further refactoring `_create_slash_command_group` by extracting small helpers for path formatting, option limits, and name validation to flatten control flow and reduce duplication.

The new helpers already reduce some duplication, but `_create_slash_command_group` still has tightly nested control flow and repeated validation/logging logic. You can simplify it further with small utilities without changing behavior.

### 1. Centralize command path formatting

Right now the command path is inlined multiple times:

```py
f"{root_name} {child_name}"
f"{root_name} {child_name} {leaf_name}"
```

Introduce a tiny formatter and use it everywhere:

```py
@staticmethod
def _format_command_path(*parts: str) -> str:
    return " ".join(parts)
```

Then update your uses:

```py
path = self._format_command_path(root_name, child_name)
logger.warning(
    f"[Discord] Skipping invalid or duplicate entry '{path}'."
)

leaf_path = self._format_command_path(root_name, child_name, leaf_name)
logger.warning(
    f"[Discord] Skipping invalid or duplicate entry '{leaf_path}'."
)
```

This reduces noise and makes intent clearer.

### 2. Extract option‑limit checks into a helper

The `_DISCORD_MAX_OPTIONS` limit and related logging is duplicated for root group and subgroup. You can centralize this:

```py
def _can_add_option(
    self,
    group: discord.SlashCommandGroup,
    path: str,
) -> bool:
    if len(group.subcommands) >= _DISCORD_MAX_OPTIONS:
        logger.warning(
            f"[Discord] Command group '{path}' exceeds "
            f"{_DISCORD_MAX_OPTIONS} options; remaining entries were skipped."
        )
        return False
    return True
```

Use it in both loops:

```py
for child_filter in group_filter.sub_command_filters:
    if not self._can_add_option(root_group, root_name):
        break
    ...

for leaf_filter in child_filter.sub_command_filters:
    subgroup_path = self._format_command_path(root_name, child_name)
    if not self._can_add_option(subgroup, subgroup_path):
        break
    ...
```

Now both limit checks share the same behavior and wording.

### 3. Extract shared name/duplicate validation

You have similar logic for root vs subgroup:

```py
if (
    not self._is_valid_slash_command_name(child_name)
    or child_name in root_names
):
    ...
if (
    not self._is_valid_slash_command_name(leaf_name)
    or leaf_name in subgroup_names
):
    ...
```

This can be consolidated into a small helper that also handles logging:

```py
def _is_valid_unique_name(
    self,
    name: str,
    used: set[str],
    path: str,
) -> bool:
    if not self._is_valid_slash_command_name(name) or name in used:
        logger.warning(
            f"[Discord] Skipping invalid or duplicate entry '{path}'."
        )
        return False
    return True
```

Then the loops become flatter:

```py
child_path = self._format_command_path(root_name, child_name)
if not self._is_valid_unique_name(child_name, root_names, child_path):
    continue

...

leaf_path = self._format_command_path(root_name, child_name, leaf_name)
if not self._is_valid_unique_name(leaf_name, subgroup_names, leaf_path):
    continue
```

This pulls validation and logging out of the nested control flow, making `_create_slash_command_group` easier to read while preserving all behavior.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread astrbot/core/platform/sources/discord/discord_platform_adapter.py Outdated
Comment thread astrbot/core/platform/sources/discord/discord_platform_adapter.py
@casama233
casama233 force-pushed the feat/discord-command-groups branch from 6474be9 to ad992f0 Compare August 13, 2026 08:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:platform The bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants